﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

using Happy.Dto;
using Happy.Dto.CommonModel.TreeLike;
using Happy.Application.Query;
using Happy.Application.Query.CommonModel.TreeLike;

namespace Happy.Web.Mvc.ExtJs.CommonModel.TreeLike
{
    /// <summary>
    /// 树形聚合根控制器。
    /// </summary>
    public abstract class TreeNodeController<TViewModel, TId> : AggregateRootController<TViewModel, TId>
        where TViewModel : class, ITreeNodeView<TId>, IId<TId>, IOptimisticKey
        where TId : struct
    {
        /// <summary>
        /// 返回孩子节点，面向树形结构。
        /// </summary>
        public ActionResult Children(QueryRequest query, TId? id)
        {
            var items = this.TreeNodeQueryService.Children(query, id);

            return this.FetchResult(items);
        }

        /// <summary>
        /// 查询服务。
        /// </summary>
        protected ITreeNodeQueryService<TViewModel, TId> TreeNodeQueryService
        {
            get
            {
                return this.Service<ITreeNodeQueryService<TViewModel, TId>>();
            }
        }

        /// <summary>
        /// 在父方法的返回基础上，将结果集合按照前序遍历顺序返回。
        /// </summary>
        protected override IEnumerable<TViewModel> FetchModels(QueryRequest query)
        {
            return base
                .FetchModels(query)
                .PreOrderSort<TViewModel, TId>();
        }
    }

    /// <summary>
    /// 树形聚合根控制器。
    /// </summary>
    public abstract class TreeNodeController<TViewModel> : TreeNodeController<TViewModel, Guid>
        where TViewModel : class, ITreeNodeView<Guid>, IId<Guid>, IOptimisticKey
    {
    }
}
